package com.inspectortime.admin;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.validation.ValidationUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

public class LoginController extends SimpleFormController {

	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {
		return new LoginForm();
	}

	protected ModelAndView onSubmit(HttpServletRequest request,	HttpServletResponse response, Object command, BindException errors)
			throws Exception {

		LoginForm form = (LoginForm) command;
		ValidationUtils.rejectIfEmpty(errors, "userName", "required");
		ValidationUtils.rejectIfEmpty(errors, "password", "required");
		if (errors.getErrorCount() > 0) {
			return new ModelAndView(getFormView(), errors.getModel());
		}

		if (!form.getUserName().equalsIgnoreCase("itadmin")) {
			errors.rejectValue("userName", "notFound", null, "User not found");
			return new ModelAndView(getFormView(), errors.getModel());			
		}

		AdminUser user = new AdminUser();
		user.setId("itadmin_user_id");
		user.setUserName(form.getUserName());
		user.setPassword("stucco12");

		if (!form.getPassword().equals(user.getPassword())) {
			errors.rejectValue("userName", "notFound", null, "Invalid password");
			return new ModelAndView(getFormView(), errors.getModel());
		}

		// Stick user in session
		HttpSessionUtils.storeLoggedInUser(request, user);

		// render success view
		if (getSuccessView() == null) {
			throw new ServletException("successView isn't set");
		}
		return new ModelAndView(getSuccessView(), errors.getModel());
	}

}
